<template>
  <k-form-modal
    drawer
    width="640px"
    title="编辑账号"
    label-width="70px"
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <h4 class="mb-20">账号设置</h4>
    <el-form-item label="账号名称">{{ state.model.name }}</el-form-item>
    <el-form-item label="手机号">{{ state.model.mobile }}</el-form-item>
    <el-form-item label="账号状态">
      <el-switch
        v-model="state.model.is_frozen"
        width="50"
        inline-prompt
        :active-value="false"
        :inactive-value="true"
        active-text="在职"
        inactive-text="离职"
      />
    </el-form-item>
    <el-form-item label="岗位选择">
      <div class="role-box">
        <div v-for="item in roleList" :key="item.role_id" class="role-item" :class="{ active: state.model.role_id === item.role_id }" @click="handleCheckRole(item)">
          {{ item.role_name }}
        </div>
        <div class="role-item add" @click="handleJump">+</div>
      </div>
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

import {} from '../hooks/use-table';
import { useFormModal } from '@crud/index';
import { getAccountRoleList, updateAccount } from '@/api/crm-kgj/auth';
import { useRouter } from 'vue-router';

const emits = defineEmits(['after-submit']);
const formRef = ref();
const roleList = ref([]);
const router = useRouter();
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {},
  getParams: (model) => model,
  onShow: (mode = 0, data: any) => {
    if (mode === 0) {
      methods.resetModel();
    } else if (data) {
      state.model = { ...state.model, ...data };
      handleGetAccountRoleList();
    }
  },
  onSubmit: async (model, mode = 0) => {
    const { user_id, role_id, is_frozen } = state.model;
    const res = await updateAccount({
      user_id,
      role_id,
      is_frozen
    });
    if (!res.err) {
      ElMessage.success('更新成功');
      emits('after-submit');
    }
    return res;
  }
});
/** 获取岗位列表 */
const handleGetAccountRoleList = async () => {
  const res = await getAccountRoleList();
  if (!res.err) {
    roleList.value = res.data;
  }
};
/** 选中岗位 */
const handleCheckRole = (item) => {
  const { role_id } = item;
  state.model.role_id = role_id;
};
/** 跳转到岗位权限 */
const handleJump = () => {
  router.push({ name: 'KgjJobAuthority' });
};
defineExpose({
  show: methods.show
});
</script>
<style lang="scss" scoped>
.role-box {
  display: flex;
  flex-wrap: wrap;

  .role-item {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;
    margin-right: 16px;
    margin-bottom: 16px;
    cursor: pointer;
    background-color: var(--fill-3);

    &.active {
      color: var(--brand-6);
      background-color: #e8f3ff;
    }

    &.add {
      padding: 0 18px;
    }
  }
}
</style>
